<template>
  <el-dialog
    v-model="props.dialogVisible"
    :title="props.dialogForm?.title"
    :width="props.dialogForm?.width"
    :show-close="false"
  >
    <el-form :model="purForm" :rules="rules" ref="purFormRef">
      <el-form-item label="厂家类型" prop="factoryType">
        <el-select
          v-model="purForm.factoryType"
          class="m-2"
          style="width: 100%"
          placeholder="请选择厂家类型"
          @change="ChangeFactory"
        >
          <el-option
            v-for="item in manufactors"
            :key="item.id"
            :label="item.configValue"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="厂家名称" prop="factoryName">
        <el-input
          v-model="purForm.factoryName"
          autocomplete="off"
          style="width: 100%"
          placeholder="请输入厂家名称"
          maxlength="16"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系人" prop="linkMan">
        <el-input
          v-model="purForm.linkMan"
          autocomplete="off"
          style="width: 100%"
          placeholder="请输入联系人名称"
          maxlength="16"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="电话" prop="linkTel">
        <el-input
          v-model="purForm.linkTel"
          autocomplete="off"
          style="width: 100%"
          placeholder="请输入联系人电话"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="地址">
        <div>
          <el-select
            v-model="purForm.provinceId"
            class="m-2"
            style="width: 33%"
            placeholder="省"
            clearable
            @change="proChange"
          >
            <el-option
              v-for="item in allAreasList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          <el-select
            v-model="purForm.cityId"
            class="m-2"
            style="width: 33%"
            placeholder="市"
            clearable
            @change="cityChange"
          >
            <el-option
              v-for="item in selectCityList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          <el-select
            v-model="purForm.areaId"
            class="m-2"
            style="width: 33%"
            placeholder="区"
            clearable
            @change="areaChange"
          >
            <el-option
              v-for="item in selectAreaList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </div>
        <el-input
          v-model="purForm.address"
          autocomplete="off"
          style="width: 100%; margin-top: 10px"
          placeholder="请输入详细地址"
          maxlength="16"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="供货范围">
        <el-input
          v-model="purForm.supplyScope"
          autocomplete="off"
          style="width: 100%"
          placeholder="请输入供货范围"
          maxlength="16"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(purFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(purFormRef)">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { ref, reactive, defineAsyncComponent, watch, computed } from 'vue'
import { editPurveyor, addPurveyor } from '/@/api/assets/index'
import allAreas from '/@/jsons/pcas-code.json'
import provinces from '/@/jsons/provinces.json'
import cities from '/@/jsons/cities.json'
import areas from '/@/jsons/areas.json'
import { dictionaryList } from '/@/api/publicApi'
const props = defineProps({
  dialogVisible: Boolean,
  dialogForm: Object,
  dialogDetail: Object
})
const emit = defineEmits(['cancel', 'submit'])
const formLabelWidth = ref('95px')
const purFormRef = ref<FormInstance>()
const purForm = ref<any>({
  factoryType: '',
  factoryTypeName: '',
  factoryName: '',
  linkMan: '',
  linkTel: '',
  provinceId: '',
  province: '',
  cityId: '',
  city: '',
  areaId: '',
  area: '',
  address: '',
  supplyScope: ''
})
//所有数据
const allAreasList = ref<any>(provinces)

//城市下拉框内容所有值
const selectCityList = ref<any>([])

//区域下拉框内容所有值
const selectAreaList = ref<any>([])
watch(
  () => props.dialogVisible,
  () => {
    if (!props?.dialogDetail?.id) {
      purForm.value = {}
    } else {
      purForm.value = JSON.parse(JSON.stringify(props?.dialogDetail))
      purForm.value.provinceId =
        purForm.value.provinceId != ''
          ? JSON.stringify(purForm.value.provinceId)
          : ''
      purForm.value.province =
        purForm.value.province != '' ? props?.dialogDetail?.province : ''
      purForm.value.cityId =
        purForm.value.cityId != '' ? JSON.stringify(purForm.value.cityId) : ''
      purForm.value.city = props?.dialogDetail?.city
        ? props?.dialogDetail?.city
        : ''
      purForm.value.areaId =
        purForm.value.areaId != '' ? JSON.stringify(purForm.value.areaId) : ''
      purForm.value.area = props?.dialogDetail?.area
        ? props?.dialogDetail?.area
        : ''
      getCity(purForm.value.provinceId)
      getArea(purForm.value.cityId)
    }
  },
  { immediate: true }
)

const rules = reactive<FormRules>({
  factoryType: [
    { required: true, message: '请选择厂家类型', trigger: 'changer' }
  ],
  factoryName: [{ required: true, message: '请输入厂家名称', trigger: 'blur' }],
  linkMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  linkTel: [{ required: true, message: '请输入电话号码', trigger: 'blur' }]
})

const manufactors = ref<any>([])

const ChangeFactory = (val: any) => {
  manufactors.value.forEach((item: any) => {
    if (item.id == val) {
      purForm.value.factoryTypeName = item.configValue
    }
  })
}

const geManufactor = () => {
  dictionaryList({ configType: 'factory_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      manufactors.value = res.data
    }
  })
}
geManufactor()

const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emit('cancel')
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (!props?.dialogDetail?.id) {
        addPurveyor(purForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage.success(`添加成功！`)
            emit('submit')
          }
        })
      } else {
        purForm.value.id = props?.dialogDetail?.id
        delete purForm.value.companyId
        delete purForm.value.createTime
        delete purForm.value.updateTime
        editPurveyor(purForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage.success(`编辑成功！`)
            emit('submit')
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const getCity = (val: any) => {
  selectCityList.value = []
  cities.forEach((item: any) => {
    if (item.provinceCode == val) {
      selectCityList.value.push(item)
    }
  })
}
const getArea = (val: any) => {
  selectAreaList.value = []
  areas.forEach((item: any) => {
    if (item.cityCode == purForm.value.cityId) {
      selectAreaList.value.push(item)
    }
  })
}

const proChange = (val: any) => {
  if (val == '') {
    selectCityList.value = []
    selectAreaList.value = []
    purForm.value.cityId = ''
    purForm.value.city = ''
    purForm.value.areaId = ''
    purForm.value.area = ''
  } else {
    getCity(val)
  }
  allAreasList.value.forEach((element: any) => {
    if (element.code == val) {
      purForm.value.province = element.name
    }
  })
}
const cityChange = (val: any) => {
  if (val == '') {
    selectAreaList.value = []
    purForm.value.areaId = ''
    purForm.value.area = ''
  } else {
    getArea(val)
  }
  selectCityList.value.forEach((element: any) => {
    if (element.code == val) {
      purForm.value.city = element.name
    }
  })
}
const areaChange = (val: any) => {
  selectAreaList.value.forEach((element: any) => {
    if (element.code == val) {
      purForm.value.area = element.name
    }
  })
}
</script>
<style scoped lang="scss">
.elrowClass {
  margin-bottom: 16px;
}

.tips {
  font-size: 13px;
  font-weight: 400;
  line-height: 21px;
  color: rgba(140, 140, 140, 1);
  text-align: left;
}
</style>
<style>
.el-dialog__title {
  font-size: 20px !important;
  font-weight: 700 !important;
}
</style>
